package singleton;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/22 21:28
 */

//使用synchronized关键字保证懒汉式的线程安全
public class LazySingletonSafeBySynTest {
    public static void main(String[] args) {

        new Thread(()->{
            System.out.println(LazySingletonSafeBySyn.getInstance());
        }).start();

        new Thread(()->{
            System.out.println(LazySingletonSafeBySyn.getInstance());
        }).start();
    }


}

class LazySingletonSafeBySyn{

    private static LazySingletonSafeBySyn instance;

    //私有化构造器
    private LazySingletonSafeBySyn(){

    }

    //提供一个公共访问点,获得该单例对象
    public static synchronized LazySingletonSafeBySyn getInstance(){
        if(instance == null){
            instance = new LazySingletonSafeBySyn();
            return instance;
        }
        return instance;
    }

}
